// src/store/modules/permission.js
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { constantRoutes, asyncRoutes } from '@/router'; // 从路由文件导入路由配置

// 辅助函数：判断角色是否有权限访问路由
function hasPermission(userRole, route) {
    if (route.meta && route.meta.roles) {
        return route.meta.roles.includes(userRole);
    }
    return true;
}

// 辅助函数：递归过滤异步路由
function filterAsyncRoutes(routes, userRole) {
    const res = [];
    routes.forEach(route => {
        const tmp = { ...route };
        if (hasPermission(userRole, tmp)) {
            if (tmp.children) {
                tmp.children = filterAsyncRoutes(tmp.children, userRole);
                if (tmp.children && tmp.children.length > 0) {
                    res.push(tmp);
                }
            } else {
                res.push(tmp);
            }
        }
    });
    return res;
}

export const usePermissionStore = defineStore('permission', () => {
    // 存储用户最终可访问的完整路由（包括常量和动态的）
    const routes = ref([]);
    // 存储用户可访问的动态路由（用于 addRoute）
    const addRoutes = ref([]);

    function generateRoutes(userRole) {
        // 计算出有权限访问的动态路由
        const accessedRoutes = filterAsyncRoutes(asyncRoutes, userRole);
        
        // 更新 state
        addRoutes.value = accessedRoutes;
        routes.value = constantRoutes.concat(accessedRoutes);
        
        // 返回计算出的动态路由，供路由守卫使用
        return accessedRoutes;
    }
    
    // 登出时重置
    function resetRoutes() {
        routes.value = [];
        addRoutes.value = [];
    }

    return { routes, addRoutes, generateRoutes, resetRoutes };
});